package com.team.app.controller;

import java.util.Locale;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;

public abstract class AbstractController<T> extends AbstractAuthCheck{
	@Autowired
    private MessageSource messageSource;
	
	public abstract String indexAction(Model model,HttpSession s,T obj);
	public abstract String addAction(Model model,HttpSession s);
	public abstract String backAction(Model model,HttpSession s, T obj ) ;
	public abstract String editAction(Model model,HttpSession s,@PathVariable("id")Long id);
	public abstract String confirmAction(Model model,HttpSession s, @ModelAttribute("obj")T obj ,BindingResult result) ;
	public abstract String completeAction(Model model,HttpSession s,@ModelAttribute("obj")T obj ,BindingResult result) ;
	public abstract String deleteAction(Model model,HttpSession s,@PathVariable("id")Long id) ;
	
	
	//
	public void setMessage(BindingResult result,String key) {
		String message = getMessage(key) != null ? getMessage(key) : key;		
		ObjectError error = new ObjectError("",message);
		result.addError(error);
	}
	
	public void setMessage(Model model,BindingResult result,String propertyName,String key) {
		String message = getMessage(key) != null ? getMessage(key) : key;	
		ObjectError error = new ObjectError(propertyName,message);
		result.addError(error);
		model.addAttribute(propertyName, propertyName +" field-error");
	}
	
	public String getMessage(String key){
		Locale locale = new Locale("vi", "VN");
		String message = null;
        try {
            message = messageSource.getMessage((String) key, new Object[]{"messages"}, locale);
        }
        catch (Exception e) {e.printStackTrace();}		
		return message;
	}
	
}
